
import { Injectable } from '@angular/core';
import { SQLiteObject, SQLite } from '@ionic-native/sqlite';
import { Platform, Events } from 'ionic-angular';

@Injectable()
export class SqliteHelperProvider {

  // sqlite_native 不支持Browser
  // 在Browser端使用WebSQL（W3c废弃的规范）
  database: SQLiteObject;
  win_db: any;//h5数据库
  win:any = window;//Window对象


  constructor(
    private platform: Platform,
    private sqlite: SQLite,
    private events: Events
  ) {
    
  }

  /**
   * 创建或打开数据库
  */
 createOrOpenDb(): Promise<any>{
  return new Promise<any>((resolve, reject)=>{
    if (this.isMobile()) {
      this.sqlite.create({name: 'buildings_data_3.db',location:'default'})
        .then((db:SQLiteObject)=>{
          this.database=db;
          //创建数据表的SQL语句
          this.creatTable().then(res=>resolve(res),err=>reject(err));

        })
        .catch(e=>{
          console.error(e);
          reject(e);
        });
    }else{
      this.win_db = this.win.openDatabase('buildings_data_4.db','1.0','楼栋信息表',60*1024*1024);
      //创建数据表的SQL语句
      this.creatTable().then(res=>resolve(res),err=>reject(err));

    }
  });
  
  }

  /**
  * 创建数据表
  */
 creatTable():Promise<any>{
  let sql:string = 'CREATE TABLE IF NOT EXISTS buildings_lite(objectId TEXT , name TEXT , point TEXT) ';
  return this.executeSql(sql,[]);
  }


   /**
   * 执行SQL语句
   * @param sql 
   * @param array 
   */
  executeSql(sql:string,params:Array<any>):Promise<any>{
    if(this.isMobile()){
      if(this.database){
        return this.execLoaclSql(sql,params);
      }
    }else{
      if(this.win_db){
        return this.execWebSql(sql,params);
      }
    }
    return new Promise(resolve=>resolve([]));
  }


  /**
   * 执行基于本地的SQLite分SQL语句
   * @param sql
   * @param params
   */
  private execLoaclSql(sql:string,params:Array<any>):Promise<any>{
    return this.database.executeSql(sql,params);
  }



  /**
  * 执行基于Web SQL的SQL语句
  * @param sql 
  * @param params 
  */
  private execWebSql(sql:string,params:Array<any>):Promise<any>{
    return new Promise(
      (resolve,reject)=>{
        this.win_db.transaction(
          (tx)=>{
            tx.executeSql(sql,params,(tx,res)=>resolve(res),(tx,err)=>reject(err));
          },(err)=>reject(err));
      }
    );
  }



  /**
   * 判断是否为真机环境
   */
  isMobile(): boolean{
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }



}
